import { computed, ref } from 'vue'
import { useUserStore } from '@/stores/user'
import type { FunctionItem } from '@/stores/user'

export const noticeInfo = ref('欢迎使用 EchoReminis，极简至美，一切尽在掌握')

// 轮播图当前索引
export const current = ref<number>(0)

// 获取用户 store
const userStore = useUserStore()

// 轮播图数据 - 使用 store 中的 homeSwipers
export const swiperList = computed(() => {
  const swipers = userStore.homeSwipers
  return swipers.length > 0
    ? swipers
    : [
        'https://img.zwfcyy.top/echo-app/material/ERWatermark8.jpg',
        'https://img.zwfcyy.top/echo-app/material/ERWatermark9.jpg',
        'https://img.zwfcyy.top/echo-app/material/ERWatermark10.jpg',
      ]
})

// 全部功能数据 - 从 store 中获取
export const allFunctionList = computed<FunctionItem[]>(() => {
  const permissions = userStore.permissions
  if (permissions && permissions.Home && Array.isArray(permissions.Home) && permissions.Home.length > 0) {
    // 确保 Home 数组中的每个元素都是 FunctionItem 类型
    return permissions.Home.map((item) => {
      if (typeof item === 'string') {
        return {
          id: item,
          name: '功能项',
          icon: 'https://img.zwfcyy.top/echo-app/icon/function/default.svg',
          path: '',
          sort: 0,
          collect: false,
        }
      }
      return item
    })
  }
  // 如果没有权限数据，显示"敬请期待"
  return [{
    path: '',
    name: '暂无',
    icon: 'https://img.zwfcyy.top/echo-app/icon/function/comingSoon.svg',
    id: '1922091791493021698',
    sort: 1,
    collect: false,
  }]
})

// 推荐功能数据 - 从全部功能中筛选出 collect 为 true 的项目
export const recommendList = computed<FunctionItem[]>(() => {
  return allFunctionList.value.filter(item => item.collect).sort((a, b) => a.sort - b.sort)
})

// 处理功能卡片点击
export function handleItemClick(item: FunctionItem) {
  if (!item.path) {
    uni.showToast({
      title: '敬请期待...',
      icon: 'none',
    })
  }
}

// 更新功能列表收藏状态
export function updateFunctionCollect(id: string, collect: boolean) {
  const index = allFunctionList.value.findIndex(item => item.id === id)
  if (index > -1) {
    // 更新 store 中的权限数据
    const permissions = userStore.permissions
    if (permissions && permissions.Home) {
      const updatedHome = permissions.Home.map((item, i) => {
        if (i === index) {
          return {
            ...(typeof item === 'string'
              ? {
                  id: item,
                  name: '功能项',
                  icon: 'https://img.zwfcyy.top/echo-app/icon/function/default.svg',
                  path: '',
                  sort: 0,
                }
              : item),
            collect,
          }
        }
        return item
      })
      userStore.updatePermissions({ ...permissions, Home: updatedHome })
    }
  }
}

// 刷新功能列表数据
export function refreshFunctionList() {
  userStore.fetchPermissions()
}
